package com.hbx.service.impl;

import com.hbx.constant.CachePrefixContent;
import com.hbx.constant.CommonContent;
import com.hbx.constant.ResponseStateConstant;
import com.hbx.constant.RspEnum;
import com.hbx.exception.RspException;
import com.hbx.service.BaseService;
import com.hbx.utils.CacheUtils;
import com.hbx.utils.FileUploadUtil;
import com.hbx.utils.MailSendUtil;
import com.hbx.utils.Result;
import com.hbx.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/*
 * @Author:hbx
 * 
 * */
@Service
@Slf4j
public class BaseServiceImpl implements BaseService {

    @Autowired
    private MailSendUtil mailSendUtil;

    @Autowired
    private FileUploadUtil fileUploadUtil;

    @Autowired
    private CacheUtils cacheUtils;

    /**
     * 发送验证码
     * @param email
     * @return
     */
    @Override
    public Result<String> sendCaptcha(String email) {
        String code = StringUtil.generatorCode(6);
        StringBuilder sb = new StringBuilder();
        sb.append("<h4>您本次的验证码为:");
        sb.append(code);
        sb.append(",有效期为");
        sb.append(CommonContent.CODE_EXPIRE / 60);
        sb.append("分钟,非本人操作请忽略</h4>");
        try {
            // 发送验证码
            mailSendUtil.send("资源共享平台", new String[]{email},sb.toString());
            log.info("【公共模块】:发送验证码成功,验证码为:{}",code);
            // 存储验证码
            cacheUtils.set(CachePrefixContent.EMAIL_PREFIX + email,code, CommonContent.CODE_EXPIRE);
            log.info("【公共模块】:验证码保存成功");
            return Result.ok().setMsg("验证码发送成功");
        } catch (Exception e) {
            log.error("【公共模块】:发送验证码失败,{}",e.getMessage());
            throw new RspException(ResponseStateConstant.SERVER_ERROR,"发送验证码错误,请稍后再试");
        }
    }

    /**
     * 文件上传
     * @param file
     * @return
     */
    @Override
    public Result<String> uploadFile(MultipartFile file) {
        Result<String> r = new Result<>();
        String[] prefixList = CommonContent.PREFIX_LIST;
        String originalFilename = file.getOriginalFilename();
        if (!StringUtils.hasLength(originalFilename)){
            log.error("【文件上传】:文件上传失败,源文件名为空,{}",originalFilename);
            throw new RspException(RspEnum.FILE_UPLOAD_ERROR);
        }
        String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (!Arrays.asList(prefixList).contains(prefix)){
            r.setMsg("暂不支持此类文件");
            r.setCode(ResponseStateConstant.OPERA_FAIL);
            log.error("【文件上传】:文件上传失败,类型不支持,{}",prefix);
        } else if (CommonContent.FILE_MAX_SIZE < file.getSize()){
            r.setMsg("文件大小超出1MB");
            r.setCode(ResponseStateConstant.OPERA_FAIL);
            log.error("【文件上传】:文件上传失败,文件大小超出1MB,{}kb",file.getSize() / 1024);
        } else {
            try {
                String fileName = StringUtil.generatorFileName() + prefix;
                String url = fileUploadUtil.uploadAndUrl(fileName, file.getBytes());
                r.setCode(200).setMsg("文件上传成功").setData(url);
                log.info("【文件上传】:文件上传成功,url:{}",url);
            } catch (Exception e) {
                throw new RspException(RspEnum.FILE_UPLOAD_ERROR);
            }
        }
        return r;
    }

    /**
     * 批量上传文件
     * @param files
     * @param r
     */
    @Override
    public void uploadFileBatchs(MultipartFile[] files, Result r) {
        String[] prefixList = CommonContent.PREFIX_LIST;
        List<String> pathList = new ArrayList<>();
        for (MultipartFile file : files) {
            String originalFilename = file.getOriginalFilename();
            if (!StringUtils.hasLength(originalFilename)){
                log.error("【文件上传】:文件上传失败,源文件名为空,{}",originalFilename);
                throw new RspException(RspEnum.FILE_UPLOAD_ERROR);
            }
            String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
            if (!Arrays.asList(prefixList).contains(prefix)){
                r.setMsg("暂不支持此类文件");
                log.error("【文件上传】:文件上传失败,类型不支持,{}",prefix);
                continue;
            } else if (CommonContent.FILE_MAX_SIZE < file.getSize()){
                r.setMsg("文件大小超出1MB");
                log.error("【文件上传】:文件上传失败,文件大小超出1MB,{}kb",file.getSize() / 1024);
                continue;
            } else {
                try {
                    String fileName = StringUtil.generatorFileName() + prefix;
                    String url = fileUploadUtil.uploadAndUrl(fileName, file.getBytes());
                    if (StringUtils.hasLength(url)){
                        pathList.add(url);
                        log.info("【文件上传】:文件上传成功,url:{}",url);
                    }
                } catch (Exception e) {
                    log.error("【文件上传】：文件上传失败,{}",e.getMessage());
                    continue;
                }
            }
        }
        log.info("【文件上传】:共{}个文件,成功{}个,失败{}个",files.length, pathList.size(), files.length - pathList.size());
        if (pathList.size() == 0 || pathList.size() != files.length){
            r.setCode(201).setMsg("文件上传失败");
        }
        r.setCode(200).setData(pathList).setMsg("文件上传成功");
    }

}
